<template>
  <div class="projects-page">
    

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.name" placeholder="搜索项目名称" :prefix-icon="Search" clearable />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.projectStatus" placeholder="项目状态" clearable>
            <el-option label="全部" value="" />
            <el-option 
              v-for="status in projectStatusDict" 
              :key="status.code" 
              :label="status.name"
              :value="status.code" 
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.category" placeholder="项目分类" clearable>
            <el-option label="全部" value="" />
            <el-option 
              v-for="category in projectCategoryDict" 
              :key="category.code" 
              :label="category.name"
              :value="category.code" 
            />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-button :icon="Search" type="primary" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 项目列表 -->
    <el-card shadow="never">
      <div class="table-header">
        <div></div>
        <el-button type="primary" :icon="Plus" @click="handleAddProject">
          新增项目
        </el-button>
      </div>
      <el-table :data="projects" style="width: 100%" :loading="tableLoading">
        <el-table-column type="index" label="序号" min-width="45" />

        <el-table-column prop="title" label="项目名称" min-width="380" >
          <template #default="{ row }">
            <div class="project-info">
              <el-icon class="project-icon" color="#409eff">
                <FolderOpened />
              </el-icon>
              <div>
                <p class="project-name">{{ row.title }}</p>
                <p class="project-desc">{{ row.description }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="category" label="分类" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)" size="small">
              {{ getCategoryName(row.category) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="projectStatus" label="项目进度" min-width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.projectStatus)" 
              size="small"
            >
              {{ getStatusDisplayName(row.projectStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="tech" label="技术栈" min-width="200">
          <template #default="{ row }">
            <div class="tech-tags">
              <el-tag v-for="tech in row.tech.slice(0, 3)" :key="tech" size="small" effect="plain">
                {{ tech }}
              </el-tag>
              <el-tag v-if="row.tech.length > 3" size="small" effect="plain">
                +{{ row.tech.length - 3 }}
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-switch v-model="row.status" active-value="enabled" inactive-value="disabled"
              @change="updateItemStatus(row)" />
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="{ row }">
            {{ row.createTime }}
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" :icon="View" @click="handleView(row)">
                查看
              </el-button>
              <el-button size="small" :icon="Edit" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button size="small" :icon="Delete" type="danger" @click="handleDelete(row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 项目编辑对话框 -->
    <el-dialog v-model="showEditDialog" :title="editingProject ? '编辑项目' : '新增项目'" width="600px"
      :before-close="handleCloseDialog">
      <el-form ref="projectFormRef" :model="projectForm" :rules="projectRules" label-width="100px">
        <el-form-item label="项目名称" prop="title">
          <el-input v-model="projectForm.title" placeholder="请输入项目名称" />
        </el-form-item>

        <el-form-item label="项目描述" prop="description">
          <el-input v-model="projectForm.description" type="textarea" :rows="3" placeholder="请输入项目描述" />
        </el-form-item>

        <el-form-item label="项目分类" prop="category">
          <el-select v-model="projectForm.category" placeholder="请选择项目分类" style="width: 100%">
            <el-option 
              v-for="category in projectCategoryDict" 
              :key="category.code" 
              :label="category.name"
              :value="category.code" 
            />
          </el-select>
        </el-form-item>

        <el-form-item label="项目进度" prop="projectStatus">
          <el-radio-group v-model="projectForm.projectStatus">
            <el-radio 
              v-for="status in projectStatusDict" 
              :key="status.code" 
              :label="status.code"
            >
              {{ status.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="技术栈" prop="tech">
          <el-select v-model="projectForm.tech" multiple filterable allow-create default-first-option
            placeholder="选择或输入技术栈" style="width: 100%">
            <el-option v-for="tech in techStackDict" :key="tech.code" :label="tech.name" :value="tech.name" />
          </el-select>
        </el-form-item>

        <el-form-item label="项目链接">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input v-model="projectForm.github" placeholder="GitHub链接" />
            </el-col>
            <el-col :span="12">
              <el-input v-model="projectForm.demo" placeholder="在线演示链接" />
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="详细介绍">
          <el-input v-model="projectForm.detail" type="textarea" :rows="4" placeholder="请输入项目详细介绍" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSaveProject" :loading="saveLoading">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 项目详情查看对话框 -->
    <el-dialog v-model="showViewDialog" :title="`项目详情 - ${viewingProject?.title || ''}`" width="800px"
      :before-close="handleCloseViewDialog">
      <div v-if="viewingProject" class="project-detail">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称">
            {{ viewingProject.title }}
          </el-descriptions-item>

          <el-descriptions-item label="项目状态">
            <el-tag 
              :type="getStatusType(viewingProject.projectStatus)" 
              size="small"
            >
              {{ getStatusDisplayName(viewingProject.projectStatus) }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="项目分类" :span="2">
            <el-tag :type="getCategoryType(viewingProject.category)" size="small">
              {{ getCategoryName(viewingProject.category) }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="创建时间" :span="2">
            {{ viewingProject.createTime }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 项目描述 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <span class="card-header">项目描述</span>
          </template>
          <p class="description-text">{{ viewingProject.description }}</p>
        </el-card>

        <!-- 详细介绍 -->
        <el-card v-if="viewingProject.detail" class="detail-card" shadow="never">
          <template #header>
            <span class="card-header">详细介绍</span>
          </template>
          <div class="detail-content" v-html="viewingProject.detail"></div>
        </el-card>

        <!-- 技术栈 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <span class="card-header">技术栈</span>
          </template>
          <div class="tech-tags">
            <el-tag v-for="tech in viewingProject.tech" :key="tech" size="small" effect="plain" class="tech-tag">
              {{ tech }}
            </el-tag>
          </div>
        </el-card>

        <!-- 项目链接 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <span class="card-header">项目链接</span>
          </template>
          <div class="links">
            <div v-if="viewingProject.github" class="link-item">
              <span class="link-label">源码链接：</span>
              <el-link :href="viewingProject.github" target="_blank" type="primary" :underline="false">
                {{ viewingProject.github }}
              </el-link>
            </div>
            <div v-if="viewingProject.demo" class="link-item">
              <span class="link-label">演示链接：</span>
              <el-link :href="viewingProject.demo" target="_blank" type="success" :underline="false">
                {{ viewingProject.demo }}
              </el-link>
            </div>
            <div v-if="!viewingProject.github && !viewingProject.demo" class="no-links">
              暂无链接信息
            </div>
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="handleCloseViewDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import {
  Plus,
  Search,
  Refresh,
  View,
  Edit,
  Delete,
  FolderOpened
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { projectApi, dictCategoryApi, dictItemApi } from '@/utils/api/index'

// 响应式数据
const tableLoading = ref(false)
const saveLoading = ref(false)
const showEditDialog = ref(false)
const editingProject = ref(null)
const showViewDialog = ref(false)
const viewingProject = ref(null)

// 表单引用
const projectFormRef = ref()

// 搜索表单
const searchForm = reactive({
  name: '',
  projectStatus: '',
  category: ''
})

// 项目表单
const projectForm = reactive({
  title: '',
  description: '',
  category: '',
  projectStatus: '',
  tech: [],
  github: '',
  demo: '',
  detail: ''
})

// 表单验证规则
const projectRules = {
  title: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择项目分类', trigger: 'blur' }
  ],
  projectStatus: [
    { required: true, message: '请选择项目进度', trigger: 'blur' }
  ],
  tech: [
    { required: true, message: '请输入技术栈', trigger: 'blur' }
  ]
}

// 技术栈选项 - 现在使用字典数据

// 项目列表数据
const projects = ref([])

// 字典数据
const projectStatusDict = ref([])
const projectCategoryDict = ref([])
const techStackDict = ref([])

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 数据结构转换函数
const transformBackendData = (backendProject) => {
  return {
    id: backendProject.id,
    title: backendProject.name,
    description: backendProject.description,
    category: backendProject.category,
    projectStatus: backendProject.projectStatus,
    tech: backendProject.techStack ? JSON.parse(backendProject.techStack) : [],
    github: backendProject.sourceUrl || '',
    demo: backendProject.demoUrl || '',
    createTime: backendProject.createTime,
    detail: backendProject.detail || '',
    status: backendProject.status
  }
}

const transformFrontendData = (frontendProject) => {
  return {
    id: frontendProject.id,
    name: frontendProject.title,
    category: frontendProject.category,
    description: frontendProject.description,
    techStack: JSON.stringify(frontendProject.tech),
    projectUrl: '',
    imageUrl: '',
    projectStatus: frontendProject.projectStatus,
    sortOrder: 0,
    startDate: null,
    endDate: null,
    demoUrl: frontendProject.demo,
    sourceUrl: frontendProject.github,
    detail: frontendProject.detail,
    status: frontendProject.status,
  }
}

// 加载项目状态字典数据
const loadProjectStatusDict = async () => {
  try {
    console.log('加载项目状态字典...')
    // 直接根据分类代码查询字典分类
    const categoryResponse = await dictCategoryApi.queryCategoryByCode('project_status')
    if (categoryResponse.code === 0 && categoryResponse.data) {
      // 直接根据分类代码查询字典项
      const itemsResponse = await dictItemApi.queryByCategoryCode('project_status')
      if (itemsResponse.code === 0) {
        projectStatusDict.value = itemsResponse.data || []
      }
    }
  } catch (error) {
    console.error('加载项目状态字典失败:', error)
  }
}

// 加载项目分类字典数据
const loadProjectCategoryDict = async () => {
  try {
    console.log('加载项目分类字典...')
    // 直接根据分类代码查询字典分类
    const categoryResponse = await dictCategoryApi.queryCategoryByCode('project_category')
    if (categoryResponse.code === 0 && categoryResponse.data) {
      // 直接根据分类代码查询字典项
      const itemsResponse = await dictItemApi.queryByCategoryCode('project_category')
      if (itemsResponse.code === 0) {
        projectCategoryDict.value = itemsResponse.data || []
      }
    }
  } catch (error) {
    console.error('加载项目分类字典失败:', error)
  }
}

// 加载技术栈字典数据
const loadTechStackDict = async () => {
  try {
    console.log('加载技术栈字典...')
    // 直接根据分类代码查询字典分类
    const categoryResponse = await dictCategoryApi.queryCategoryByCode('tech_stack')
    if (categoryResponse.code === 0 && categoryResponse.data) {
      // 直接根据分类代码查询字典项
      const itemsResponse = await dictItemApi.queryByCategoryCode('tech_stack')
      if (itemsResponse.code === 0) {
        techStackDict.value = itemsResponse.data || []
      }
    }
  } catch (error) {
    console.error('加载技术栈字典失败:', error)
  }
}

// 加载项目数据
const loadProjects = async () => {
  try {
    tableLoading.value = true

    const params = {}
    if (searchForm.name) {
      params.name = searchForm.name
    }
    if (searchForm.projectStatus) {
      params.projectStatus = searchForm.projectStatus
    }
    if (searchForm.category) {
      params.category = searchForm.category
    }

    const response = await projectApi.queryPage(
      pagination.page,
      pagination.size,
      params
    )

    if (response.code === 0) {
      const pageData = response.data
      projects.value = pageData.data.map(transformBackendData)
      pagination.total = pageData.total
    } else {
      ElMessage.error(response.message || '加载项目列表失败')
    }
  } catch (error) {
    console.error('加载项目列表失败:', error)
    ElMessage.error('加载项目列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 生命周期钩子
onMounted(async () => {
  await Promise.all([
    loadProjects(),
    loadProjectStatusDict(),
    loadProjectCategoryDict(),
    loadTechStackDict()
  ])
})

// 方法
const handleSearch = () => {
  pagination.page = 1
  loadProjects()
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.projectStatus = ''
  searchForm.category = ''
  pagination.page = 1
  loadProjects()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadProjects()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadProjects()
}

const handleView = (project) => {
  viewingProject.value = project
  showViewDialog.value = true
}

const handleAddProject = () => {
  editingProject.value = null
  resetProjectForm()
  showEditDialog.value = true
}

const handleEdit = (project) => {
  editingProject.value = project
  Object.assign(projectForm, {
    title: project.title,
    description: project.description,
    category: project.category,
    projectStatus: project.projectStatus,
    tech: project.tech || [],
    github: project.github || '',
    demo: project.demo || '',
    detail: project.detail || ''
  })
  showEditDialog.value = true
}

const handleDelete = async (project) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目「${project.title}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await projectApi.delete(project.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadProjects()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除项目失败:', error)
      ElMessage.error('删除项目失败')
    }
  }
}

const handleSaveProject = async () => {
  try {
    await projectFormRef.value.validate()

    saveLoading.value = true

    const backendData = transformFrontendData(projectForm)

    let response
    if (editingProject.value) {
      // 编辑模式
      response = await projectApi.update(editingProject.value.id, backendData)
    } else {
      // 新增模式
      response = await projectApi.create(backendData)
    }

    if (response.code === 0) {
      ElMessage.success(editingProject.value ? '更新成功' : '添加成功')
      handleCloseDialog()
      loadProjects()
    } else {
      ElMessage.error(response.message || '保存失败')
    }

  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 更新字典值状态
const updateItemStatus = async (item) => {
  try {
    await projectApi.update(item.id, item)
    ElMessage.success(`项目已${item.status === 'enabled' ? '启用' : '禁用'}`)
  } catch (error) {
    console.error('状态更新失败:', error)
    // 如果更新失败，恢复原状态
    item.status = item.status === 'enabled' ? 'disabled' : 'enabled'
  }
}

const resetProjectForm = () => {
  Object.assign(projectForm, {
    title: '',
    description: '',
    category: '',
    projectStatus: '',
    tech: [],
    github: '',
    demo: '',
    detail: ''
  })
}

const handleCloseDialog = () => {
  showEditDialog.value = false
  editingProject.value = null

  // 重置表单
  resetProjectForm()

  // 清除验证
  projectFormRef.value?.clearValidate()
}

const handleCloseViewDialog = () => {
  showViewDialog.value = false
  viewingProject.value = null
}

// 工具函数
const getCategoryType = (category) => {
  // 优先从字典数据中获取颜色
  if (projectCategoryDict.value && projectCategoryDict.value.length > 0) {
    const dictItem = projectCategoryDict.value.find(item => item.code === category)
    // 如果字典项有color字段，优先使用
    if (dictItem && dictItem.color) {
      return dictItem.color
    }
  }
  return 'info'
}

const getCategoryName = (category) => {
  // 优先从字典数据中获取显示名称
  if (projectCategoryDict.value && projectCategoryDict.value.length > 0) {
    const dictItem = projectCategoryDict.value.find(item => item.code === category)
    if (dictItem) {
      return dictItem.name
    }
  }
  return category
}

const getStatusType = (status) => {
  // 优先从字典数据中获取颜色
  if (projectStatusDict.value && projectStatusDict.value.length > 0) {
    const dictItem = projectStatusDict.value.find(item => item.code === status)
    // 如果字典项有color字段，优先使用
    if (dictItem && dictItem.color) {
      return dictItem.color
    }
  }
  return 'info'
}

const getStatusDisplayName = (status) => {
  // 优先从字典数据中获取显示名称
  if (projectStatusDict.value && projectStatusDict.value.length > 0) {
    const dictItem = projectStatusDict.value.find(item => item.code === status)
    if (dictItem) {
      return dictItem.name
    }
  }
  return status
}

</script>

<style scoped>
.projects-page {
  padding: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.action-buttons {
  display: flex;
  gap: 1px;
  align-items: center;
}

.action-buttons .el-button {
  flex-shrink: 0;
}

/* 项目详情查看样式 */
.project-detail {
  padding: 0;
}

.detail-card {
  margin-bottom: 16px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  font-weight: 600;
  color: #303133;
}

.description-text {
  line-height: 1.6;
  color: #606266;
  margin: 0;
  white-space: pre-wrap;
}

.detail-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
}

.tech-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tech-tag {
  margin: 0;
}

.links {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.link-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.link-label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.no-links {
  color: #909399;
  font-style: italic;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-descriptions__content) {
  color: #606266;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 16px 20px;
}
</style>